var SheetPageDisplayManager = {

	init : function() {
		this.loadContainers();
	},
	
	isContainer:function(element){
		return element.hasClass('sheetcontainer');
	},
	
	displayNewContainer : function(html,posX,posY) {
		var obj = this;
		
		//Get default size of the container
		var cWidth= SheetGridSettings.containerWidth;
		var cHeight= SheetGridSettings.containerHeight;
		
		//Compute default position of the container
		var cLeft=posX;
		var cTop=posY;
		
		// The returned HTML contains the container + the contextual menu
		// Hence we need to resize only the container
		var html = $(html); 
		html.each(function(index,element){
			var el = $(element);
			if(obj.isContainer(el)) {
				el.attr("style",
						"position:absolute;"
						+"top:"+cTop+"px;"
						+"left:"+cLeft+"px;"
						+"width:"+cWidth+"px;"
						+"height:"+cHeight+"px;"
						+"z-index:"+el.css('z-index'));
				
				obj.updatePositioning(el);
				
				obj.displayContainer(el);

				SheetEditorHandler.saveContainerLayout(el);
			} else {
				// This is the ContextualMenu
				// We append it at then end of the masterZone
				// If not there the menu get positioned wrongly
				$(SheetGridSettings.cmZoneSelector).append(el);
			}
		});
	},
	
	makeManageable : function(element) {
		var settings = SheetGridSettings;
		var minWidth = 20;
		var minHeight = 20;
		
		element.draggable({
			cursor:"move",
			stack:settings.sheetContainerSelector,
			containment:settings.gridDivSelector,
			snap:settings.gridDivSelector,
			snapMode:"both",
			snapTolerance:10,
			stop:function(event,ui){ 
				// Workaround because option containement does not
				// operate properly when combining draggable and resizable
				var target = $(event.target);
				target.resizable("option","maxWidth",SheetPageDisplayManager.maxWidth(target));
				target.resizable("option","maxHeight",SheetPageDisplayManager.maxHeight(target));
				SheetEditorHandler.saveContainerLayout(target);
			}
		});
		element.resizable({
			minWidth:minWidth,
			minHeight:minHeight,
			maxWidth:SheetPageDisplayManager.maxWidth(element),
			maxHeight:SheetPageDisplayManager.maxHeight(element),
			stop:function(event,ui){
				var target = $(event.target);
				SheetEditorHandler.saveContainerLayout(target);
			}
		});
		
		//Allow to Edit the Header of the Container
		ContainerEditor.makeEditable(element);
	},
	
	maxWidth : function(element) {
		var settings = SheetGridSettings;
		var result = settings.gridWidth - element.position().left - 1;
		return parseInt(result);
	},
	
	maxHeight : function(element) {
		var settings = SheetGridSettings;
		var result = settings.gridHeight -  element.position().top - 1;
		return parseInt(result);
	},
	
	loadContainers : function(){
		var settings = SheetGridSettings;
		var obj = this;
		// Requete Ajax pour charger la liste des Uid des Container de la Page courrante
		$.ajax({
			url:settings.baseurl.replace(/replace_event/i,"loadContainerUids"),
			success:function(response) {
				for (var prop in response) {
				    if (response.hasOwnProperty(prop)) {
				    	obj.loadContainer(response[prop]); 
				    }
				}
			},
			error:function(response){
				console.error('Ajax request failed');
			}
		});
	},
	
	loadContainer : function(uid){
		var settings = SheetGridSettings;
		var obj = this;
		$.ajax({
			url:settings.baseurl.replace(/replace_event/i,"loadContainer"),
			type:"POST",
			data:{
				uid:uid
			},
			success:function(response) {
				var html = $(response.content);
				html.each(function(index,element){
					var el = $(element);
					if(obj.isContainer(el)) {
						obj.displayContainer(el);
					} else {
						// This is the ContextualMenu
						// We append it at then end of the masterZone
						// If not there the menu get positioned wrongly
						$(SheetGridSettings.cmZoneSelector).append(el);
					}
				});
				$.tapestry.utils.loadScriptsInReply(response);
			},
			error:function(response){
				console.error('Ajax request failed');
			}
		});
	},
	
	pasteContainer : function(uid,el,posX,posY){
		var settings = SheetGridSettings;
		var obj = this;
		
		//Compute default position of the container
		var cTop=posY-el.offset().top;
		var cLeft=posX-el.offset().left;
		
		$.ajax({
			url:settings.baseurl.replace(/replace_event/i,"loadContainer"),
			type:"POST",
			data:{
				uid:uid
			},
			success:function(response) {
				var html = $(response.content);
				html.each(function(index,element){
					var el = $(element);
					if(obj.isContainer(el)) {
						obj.displayContainer(el,cTop,cLeft);
						SheetEditorHandler.saveContainerLayout(el);
					} else {
						// This is the ContextualMenu
						// We append it at then end of the masterZone
						// If not there the menu get positioned wrongly
						$(SheetGridSettings.cmZoneSelector).append(el);
					}
				});
				$.tapestry.utils.loadScriptsInReply(response);
			},
			error:function(response){
				console.error('Ajax request failed');
			}
		});
	},
	
	displayContainer : function(container,top,left) {
		var settings = SheetGridSettings;
		var obj = this;
		obj.updatePositioning(container,top,left);
		$(settings.gridDivSelector).prepend(container);
    	if(settings.editmode) {
    		obj.makeManageable(container)    		
    	}
	},

	removeContainer : function(uid){
		$('#'+uid).remove();
	},

	refreshContainer : function(uid){
		var obj = this;
		obj.removeContainer(uid);
		obj.loadContainer(uid);
	},
	
	clearPage : function(){
		var settings = SheetGridSettings;
		$(settings.sheetContainerSelector).each(function(index,element) {
			$(element).remove();
		});
	},
	
	updatePositioning: function(container,top,left) {
		//Get Size and Coordinates of the container
		var cWidth=parseInt(container.width());
		var cHeight=parseInt(container.height());
		var cTop=0;
		var cLeft=0;
		var zIndex=0;
		var styles = container.attr('style').split(";");
		for(index in styles){
			var style = styles[index];
			if(style.indexOf("top") != -1){
				cTop = parseInt(style.split(":")[1]);
			}
			if(style.indexOf("left") != -1){
				cLeft = parseInt(style.split(":")[1]);
			}
			if(style.indexOf("z-index") != -1){
				zIndex = parseInt(style.split(":")[1]);
			}
		}

		// If top or left are defined, it means we are trying 
		// to change original position of the Container 
		// Probably coming from a "Paste"
		if(top != undefined){
			cTop = Number(top);
		}
		
		if(left != undefined){
			cLeft = Number(left);
		}
		
		//Check if the Container will still be in the Grid
		//If not then adjust position accordingly.
		var maxRight = $(SheetGridSettings.gridDivSelector).width();
		var maxBottom = $(SheetGridSettings.gridDivSelector).height();
		
		if(cLeft+cWidth > maxRight) {
			var diff = (cLeft + cWidth) - maxRight;
			cLeft = cLeft - diff -1;
		}
		
		if(cTop+cHeight > maxBottom) {
			var diff = (cTop + cHeight) - maxBottom;
			cTop = cTop - diff - 1;
		}

		container.attr("style",
				"position:absolute;"
				+"top:"+cTop+"px;"
				+"left:"+cLeft+"px;"
				+"width:"+cWidth+"px;"
				+"height:"+cHeight+"px;"
				+"z-index:"+zIndex);
		
	}
};